<template>
    <div id="goods_container">
        <div class="header-section">
            <h2>商品管理</h2>
            <div class="search-bar">
                <el-input v-model="searchKeyword" placeholder="输入商品名" clearable
                    @clear="fetchGoods">
                    <template #prefix>
                        <el-icon>
                            <search />
                        </el-icon>
                    </template>
                </el-input>
                <el-button type="primary" @click="searchGoods">搜索</el-button>
                <el-button type="success" @click="addGoodsHandle">新增商品</el-button>
            </div>
        </div>

        <!-- 主表格 -->
        <el-table :data="goodsList" border style="width: 100%" v-loading="loading">
            <!-- 扩展列，点击展开展示商品规格和商品标签信息 -->
            <el-table-column type="expand">
                <template #default="props">
                    <el-tabs>
                        <!-- 规格信息 Tab -->
                        <el-tab-pane label="规格信息">
                            <div v-for="spec in props.row.specificationsWithValues" :key="spec.id"
                                class="spec-container">
                                <h4>{{ spec.speci_name }}</h4>
                                <el-table :data="spec.specis" border>
                                    <el-table-column prop="specis_value" label="规格值" />
                                    <el-table-column prop="price" label="价格" />
                                    <el-table-column label="操作" width="150">
                                        <template #default>
                                            <el-button type="primary" size="small">编辑</el-button>
                                            <el-button type="danger" size="small">删除</el-button>
                                        </template>
                                    </el-table-column>
                                </el-table>
                            </div>
                        </el-tab-pane>

                        <!-- 标签信息 Tab -->
                        <el-tab-pane label="标签信息">
                            <el-table :data="props.row.labels" border>
                                <el-table-column prop="label" label="标签名称" />
                                <el-table-column label="操作" width="150">
                                    <template #default>
                                        <el-button type="primary" size="small">编辑</el-button>
                                        <el-button type="danger" size="small">删除</el-button>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </el-tab-pane>
                    </el-tabs>
                </template>
            </el-table-column>

            <el-table-column prop="goods_id" label="商品ID" width="120" />
            <el-table-column prop="goods_name" label="商品名称" min-width="220" show-overflow-tooltip />

            <el-table-column label="封面图" width="100">
                <template #default="scope">
                    <el-image style="width: 60px; height: 60px" :src="ossRoot + scope.row.cover"
                        :preview-src-list="[ossRoot + scope.row.cover]" fit="cover">
                    </el-image>
                </template>
            </el-table-column>

            <el-table-column label="标签" width="180">
                <template #default="scope">
                    <el-tag v-for="tag in scope.row.labels" :key="tag.id" type="success" class="tag-item">
                        {{ tag.label }}
                    </el-tag>
                </template>
            </el-table-column>

            <el-table-column prop="price" label="价格" width="100" />
            <el-table-column prop="inventory" label="库存" width="80" />
            <el-table-column prop="sale_volume" label="销量" width="80" />
            <el-table-column prop="type" label="分类" width="100" />

            <el-table-column label="是否推荐" width="100">
                <template #default="scope">
                    <el-switch v-model="scope.row.recommend" @change="toggleRecommend(scope.row)" />
                </template>
            </el-table-column>

            <el-table-column label="轮播图" width="100">
                <template #default="scope">
                    <el-button type="primary" size="small" @click="showSlideshowDialog(scope.row)">
                        查看图片 ({{ scope.row.slideshows.length }})
                    </el-button>
                </template>
            </el-table-column>

            <el-table-column label="详情图" width="100">
                <template #default="scope">
                    <el-button type="info" size="small" @click="showDetailImgDialog(scope.row)">
                        查看图片 ({{ scope.row.detailImgs.length }})
                    </el-button>
                </template>
            </el-table-column>

            <el-table-column label="操作" width="200" fixed="right">
                <template #default="scope">
                    <el-button type="primary" size="small" @click="handleEditeGOodsInfo(scope.row)">编辑</el-button>
                    <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页组件 -->
        <div class="pagination-container">
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                :current-page="currentPage" :page-sizes="[8, 16, 32, 64]" :page-size="pageSize"
                layout="total, sizes, prev, pager, next, jumper" :total="total">
            </el-pagination>
        </div>

        <!-- 轮播图预览弹窗 -->
        <el-dialog title="轮播图预览" v-model="slideshowDialogVisible" width="70%">
            <div class="image-preview-container">
                <div v-for="image in currentImages" :key="image.id" class="image-preview-item">
                    <el-image :src="ossRoot + image.image_url" :preview-src-list="currentImagesUrls" fit="contain">
                    </el-image>
                    <div class="image-actions">
                        <el-button type="danger" size="small" icon="el-icon-delete" circle></el-button>
                    </div>
                </div>
                <div class="image-upload-box">
                    <el-upload action="#" :auto-upload="false" :show-file-list="false">
                        <el-button type="primary">上传新图片</el-button>
                    </el-upload>
                </div>
            </div>
        </el-dialog>

        <!-- 详情图预览弹窗 -->
        <el-dialog title="详情图预览" v-model="detailImgDialogVisible" width="70%">
            <div class="image-preview-container">
                <div v-for="image in currentImages" :key="image.id" class="image-preview-item">
                    <el-image :src="ossRoot + image.image_url" :preview-src-list="currentImagesUrls" fit="contain">
                    </el-image>
                    <div class="image-actions">
                        <el-button type="danger" size="small" icon="el-icon-delete" circle></el-button>
                    </div>
                </div>
                <div class="image-upload-box">
                    <el-upload action="#" :auto-upload="false" :show-file-list="false">
                        <el-button type="primary">上传新图片</el-button>
                    </el-upload>
                </div>
            </div>
        </el-dialog>

        <!-- 新增商品对话框 -->
        <el-dialog v-model="dialogVisible" title="新增商品" width="70%" :before-close="handleClose" destroy-on-close>
            <el-form ref="formRef" :model="goodsForm" :rules="rules" label-width="120px" label-position="right">
                <!-- 基本信息 -->
                <el-divider content-position="left">基本信息</el-divider>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="商品ID" prop="goods_id">
                            <el-input v-model="goodsForm.goods_id" placeholder="请输入商品ID，如：hwcomputer-1" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="商品名称" prop="goods_name">
                            <el-input v-model="goodsForm.goods_name" placeholder="请输入商品名称" />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="8">
                        <el-form-item label="商品价格" prop="price">
                            <el-input-number v-model="goodsForm.price" :min="0" :precision="2" :step="10"
                                controls-position="right" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="库存数量" prop="inventory">
                            <el-input-number v-model="goodsForm.inventory" :min="0" :precision="0" :step="1"
                                controls-position="right" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="排序" prop="sort">
                            <el-input-number v-model="goodsForm.sort" :min="1" :precision="0" :step="1"
                                controls-position="right" />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="8">
                        <el-form-item label="商品类型" prop="type">
                            <el-select v-model="goodsForm.type" placeholder="请选择商品类型" style="width: 100%">
                                <el-option v-for="item of goodsTypeList" :key="index" :label="item.type_name"
                                    :value="item.type_name" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="所属店铺" prop="owner_store_id">
                            <el-select v-model="goodsForm.owner_store_id" placeholder="请选择商品类型" style="width: 100%">
                                <el-option v-for="item of storeList" :key="index" :label="item.store_name"
                                    :value="item.store_id" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="是否推荐" prop="recommend">
                            <el-switch v-model="goodsForm.recommend" @change="addRecommentdHandle" />
                        </el-form-item>
                    </el-col>
                </el-row>

                <!-- 新增- 商品封面 -->
                <el-form-item label="封面图片" prop="cover">
                    <el-upload class="avatar-uploader" :http-request="addPopCoverUpload" :limit="1"
                        :show-file-list="false" :multiple="false" :on-success="handleCoverSuccess">
                        <img v-if="addPopGoodsImgFlag" :src="addPopGoodsImgUrl" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload>
                </el-form-item>

                <!-- 商品标签 -->
                <el-divider content-position="left">商品标签</el-divider>
                <el-form-item>
                    <div v-for="(label, index) in goodsForm.labels" :key="index"
                        style="display: flex; margin-bottom: 10px;">
                        <el-input v-model="label.label" placeholder="请输入标签名称" style="width: 200px;" />
                        <el-button type="danger" :icon="Delete" @click="removeLabel(index)"
                            style="margin-left: 10px;">删除</el-button>
                    </div>
                    <el-button style="position: relative; bottom: 4px;" type="primary" :icon="Plus"
                        @click="addLabel">添加标签</el-button>
                </el-form-item>

                <!-- 轮播图 -->
                <el-divider content-position="left">轮播图</el-divider>
                <el-form-item>
                    <el-upload ref="addPopSlideRef" list-type="picture-card" v-model:file-list="addPopSlideUploadList"
                        :auto-upload="false" :on-preview="handlePictureCardPreview" :on-remove="handleRemoveSlideshow"
                        :on-success="handleSlideshowSuccess" multiple>
                        <el-icon>
                            <Plus />
                        </el-icon>
                    </el-upload>
                    <el-button style="position: relative; left: 10px;" type="success"
                        @click="customSlidUpload">上传</el-button>
                    <el-dialog v-model="dialogImageVisible" title="预览图片">
                        <img :src="dialogImageUrl" alt="Preview" />
                    </el-dialog>
                </el-form-item>

                <!-- 详情图片 -->
                <el-divider content-position="left">详情图片</el-divider>
                <el-form-item>
                    <el-upload ref="addPopDetailRef" list-type="picture-card" v-model:file-list="addPopDetailUploadList"
                        :auto-upload="false" :on-preview="handlePictureCardPreview" :on-remove="handleRemoveDetailImg"
                        :on-success="handleDetailImgSuccess" multiple>
                        <el-icon>
                            <Plus />
                        </el-icon>
                    </el-upload>
                    <el-button style="position: relative; left: 10px;" type="success"
                        @click="customDetailUpload">上传</el-button>
                </el-form-item>

                <!-- 规格参数 -->
                <el-divider content-position="left">规格参数</el-divider>
                <div v-for="(specification, specIndex) in goodsForm.specificationsWithValues" :key="specIndex">
                    <el-divider content-position="left">
                        规格 {{ specIndex + 1 }}
                        <el-button type="danger" size="small" :icon="Delete" @click="removeSpecification(specIndex)"
                            style="margin-left: 10px;">删除</el-button>
                    </el-divider>

                    <el-form-item label="规格名称">
                        <el-input v-model="specification.speci_name" placeholder="如：硬盘、颜色等" />
                    </el-form-item>

                    <div v-for="(specValue, valueIndex) in specification.specis" :key="valueIndex"
                        style="margin-left: 20px;">
                        <el-row :gutter="20">
                            <el-col :span="10">
                                <el-form-item label="规格值">
                                    <el-input v-model="specValue.specis_value" placeholder="如：256GB" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="10">
                                <el-form-item label="价格">
                                    <el-input-number v-model="specValue.price" :min="0" :precision="2" :step="10"
                                        controls-position="right" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="4">
                                <el-button type="danger" :icon="Delete" @click="removeSpecValue(specIndex, valueIndex)"
                                    style="margin-top: 4px;">删除</el-button>
                            </el-col>
                        </el-row>
                    </div>

                    <el-button type="primary" size="small" :icon="Plus" style="margin-bottom: 8px;"
                        @click="addSpecValue(specIndex)">添加规格值</el-button>
                </div>

                <el-button type="primary" :icon="Plus" @click="addSpecification">添加规格类型</el-button>
            </el-form>

            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="submitForm">确认</el-button>
                </span>
            </template>
        </el-dialog>
        <!-- 编辑弹窗 -->
        <GoodsEditDialog v-model:visible="editDialogVisible" :goodsData="currentGoods" @success="fetchGoods()" />
    </div>
</template>

<script setup>
import { ref, onMounted, computed, reactive } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus, Search } from '@element-plus/icons-vue'
import axios from "../../public/request";
import sourceAxios from "axios";
import { getUniqueFileName } from "../../public/utils";
import GoodsEditDialog from "./GoodsEditDialog.vue";

// 控制编辑对话框显示
const editDialogVisible = ref(false)
// 当前编辑的商品数据
const currentGoods = ref({})

// 数据相关
const goodsList = ref([]);
const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(8);
const total = ref(0);
const ossRoot = ref("https://uni-mall-maohe.oss-cn-guangzhou.aliyuncs.com/uni_mall/");
const searchKeyword = ref('');

// 新增相关
const dialogVisible = ref(false);
const formRef = ref(null);
const dialogImageUrl = ref('');
const dialogImageVisible = ref(false);

// 新增 封面上传的标识 -图片回显
let addPopGoodsImgFlag = ref(false);
let addPopGoodsImgUrl = ref();

// 新增表单：轮播图文件列表
let addPopSlideUploadList = ref([]);
// 新增表单：新增轮播图生成的唯一文件名列表
let addPopSlidFileNameList = ref([]);
// 新增表单：轮播图回显列表
let showSlidPictureList = ref([]);
// 轮播图列表控制显示
let showSlidPictureListFlag = ref(false);
// 新增轮播图上传组件
let addPopSlideRef = ref();

// 新增详情图上传组件
let addPopDetailRef = ref();
// 新增详情图的列表
let addPopDetailUploadList = ref([]);


// 商品类型选择
const goodsTypeList = ref([]);
// 店铺列表
const storeList = ref([]);


// 表单数据 -新增
const goodsForm = reactive({
    goods_id: '',
    goods_name: '',
    inventory: 0,
    sale_volume: 0,
    cover: '',
    price: 0,
    owner_store_id: '',
    recommend: false,
    type: '',
    sort: 1,
    labels: [],
    slideshows: [],
    detailImgs: [],
    specificationsWithValues: []
});

// 表单验证规则
const rules = {
    goods_id: [
        { required: true, message: '请输入商品ID', trigger: 'blur' },
        { pattern: /^[a-zA-Z0-9\-]+$/, message: '商品ID只能包含字母、数字和横杠', trigger: 'blur' }
    ],
    goods_name: [
        { required: true, message: '请输入商品名称', trigger: 'blur' },
        { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
    ],
    price: [
        { required: true, message: '请输入商品价格', trigger: 'change' },
        { type: 'number', min: 0, message: '价格必须大于等于0', trigger: 'change' }
    ],
    inventory: [
        { required: true, message: '请输入库存数量', trigger: 'change' },
        { type: 'number', min: 0, message: '库存必须大于等于0', trigger: 'change' }
    ],
    type: [
        { required: true, message: '请选择商品类型', trigger: 'change' }
    ],
    owner_store_id: [
        { required: true, message: '请输入所属店铺ID', trigger: 'blur' }
    ]
};


// 图片预览弹窗相关
const slideshowDialogVisible = ref(false);
const detailImgDialogVisible = ref(false);
const currentImages = ref([]);

// 页面加载时获取数据
onMounted(() => {
    fetchGoods();
    getAllType(); // 获取商品分类数据
    getALlStore(); // 获取所有店铺数据
});

// 新增弹窗 - 上传文件后触发
async function addPopSlideUpload(options) {
    console.log("新增触发===>>");

}

// 手动执行详情图上传
function customDetailUpload() {
    console.log("选择详情图列表===>>",);
    // 获取唯一文件名
    let tempUniqueFileNameList = [];
    for (const fileItem of addPopDetailUploadList.value) {
        let fileName = getUniqueFileName(fileItem.name)
        tempUniqueFileNameList.push(fileName);

        // 执行文件上传
        uploadFileToOss(fileName, fileItem.raw, showsDetailPicture)
    }

    ElMessage.success("上传成功!");

    // 将上传的图片名称列表赋予新增表单
    goodsForm.detailImgs = tempUniqueFileNameList;

    console.log("=====><>", goodsForm.detailImgs);

}

// 手动执行轮播图上传
function customSlidUpload() {
    addPopSlidFileNameList.value = [];

    showSlidPictureList.value = [];
    // 遍历文件列表添加到OSS中
    for (const fileItem of addPopSlideUploadList.value) {
        // 生成唯一文件名
        let fileName = getUniqueFileName(fileItem.name)
        addPopSlidFileNameList.value.push(fileName);
        // 遍历上传
        uploadFileToOss(fileName, fileItem.raw, showslidPicture)
    }

    ElMessage.success("上传成功!");

    // 将文件名称列表赋予新增表单
    goodsForm.slideshows = addPopSlidFileNameList.value;

    console.log("上传的文件名列表：", addPopSlidFileNameList.value)
}

const showslidPicture = (showUrl) => {
    // 将所有上传成功的轮播图URL追加到列表中显示
    showSlidPictureList.value.push(showUrl);
    // 显示轮播图
    showSlidPictureListFlag.value = true;
}

const showsDetailPicture = () => {

}

// 新增商品数据 - 文件上传触发
async function addPopCoverUpload(options) {
    const { file, onSuccess, onError } = options;
    console.log("选择的文件===>", file);

    // 生成唯一文件名，并赋予新增表单对象
    goodsForm.cover = getUniqueFileName(file.name);

    // 执行上传
    uploadFileToOss(goodsForm.cover, file, showCoverPicture);
}

// 封面上传成功后的回调
const showCoverPicture = (showUrl) => {
    // 赋值回显URL
    addPopGoodsImgUrl.value = showUrl;
    // 显示图片
    addPopGoodsImgFlag.value = true;
    ElMessage.success('上传成功');
}

// 上传文件到OSS
async function uploadFileToOss(fileName, file, callBack) {


    // 构造请求参数对象，将图片上传到OSS
    const formData = new FormData();
    // 解析签名对象参数
    let signatureParam = JSON.parse(localStorage.getItem("signatureParam"));

    // 组装表单数据
    formData.append("name", fileName);
    formData.append("policy", signatureParam.policy);
    formData.append("OSSAccessKeyId", signatureParam.ossAccessKeyId);
    formData.append("success_action_status", "200");
    formData.append("signature", signatureParam.signature);
    formData.append("key", signatureParam.dir + fileName); // 填写目录加文件名，需要注意的是目录需要和后端签名时设置的保持一致
    formData.append("file", file);

    // 执行上传
    // 发送上传请求到OSS
    const uploadRes = await sourceAxios.post(signatureParam.host, formData);

    if (uploadRes.status === 200) {
        // 调用回调函数，回显图片：封面一张，其他多张，在回调中处理
        callBack(`${signatureParam.host}/${signatureParam.dir}${fileName}`)
        return 1;
    }
}


// 添加表单-是否推荐switch选择
function addRecommentdHandle(e) {
    console.log("推荐switch");
    goodsForm.recommend = e;
}


const currentImagesUrls = computed(() => {
    return currentImages.value.map(img => ossRoot.value + img.image_url);
});

// 获取商品列表数据
const fetchGoods = async () => {
    loading.value = true;
    try {
        const { data: res } = await axios.post("/goodsManage/getListByPage", {
            page: currentPage.value,
            size: pageSize.value,
            keyword: searchKeyword.value // 搜索关键词-模糊查询
        });

        if (res.code === 1) {
            goodsList.value = res.data.goodsInfos;
            total.value = res.data.count;
        } else {
            ElMessage.error(res.msg || '获取商品列表失败');
        }
    } catch (error) {
        console.error('获取商品列表出错:', error);
        ElMessage.error('获取商品列表出错');
    } finally {
        loading.value = false;
    }
};

// 获取所有店铺数据
async function getALlStore() {
    let res = await axios.get("/store/getAll");
    if (res.data.code == 0) {
        ElMessage.error(res.msg || '获取店铺数据失败');
        return;
    }

    // 处理店铺数据
    storeList.value = res.data.data;
}

// 获取所有商品分类数据
async function getAllType() {
    let res = await axios.get("/goodsType/all");
    if (res.data.code == 0) {
        ElMessage.error(res.msg || '获取商品分类失败');
        return;
    }

    goodsTypeList.value = res.data.data;
    goodsForm.type = goodsTypeList.value[0].type_name; // 默认选择第一个商品类型
}

// 新增商品处理器
function addGoodsHandle() {
    // 重置表单
    resetForm();
    // 显示对话框
    dialogVisible.value = true;
}


// 重置表单
function resetForm() {
    // 重置所有表单字段为初始值
    Object.assign(goodsForm, {
        goods_id: '',
        goods_name: '',
        inventory: 0,
        sale_volume: 0,
        cover: '',
        price: 0,
        owner_store_id: '',
        recommend: false,
        type: '',
        sort: 1,
        labels: [],
        slideshows: [],
        detailImgs: [],
        specificationsWithValues: []
    });

    // 如果表单引用存在，重置验证状态
    if (formRef.value) {
        formRef.value.resetFields();
    }
}

// 对话框关闭前的处理函数
function handleClose() {
    ElMessageBox.confirm('确认关闭？未保存的数据将会丢失', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        dialogVisible.value = false;
    }).catch(() => {
        // 取消关闭
    });
}

// 封面上传成功回调
function handleCoverSuccess(response, uploadFile) {
    goodsForm.cover = response.url; // 假设后端返回了图片URL
}

// 上传前检查
function beforeAvatarUpload(file) {
    const isJPG = file.type === 'image/jpeg';
    const isPNG = file.type === 'image/png';
    const isLt2M = file.size / 1024 / 1024 < 2;

    if (!isJPG && !isPNG) {
        ElMessage.error('上传头像图片只能是 JPG 或 PNG 格式!');
        return false;
    }
    if (!isLt2M) {
        ElMessage.error('上传头像图片大小不能超过 2MB!');
        return false;
    }
    return true;
}

// 图片预览
function handlePictureCardPreview(file) {
    dialogImageUrl.value = file.url;
    dialogImageVisible.value = true;
}

// 轮播图上传成功
function handleSlideshowSuccess(response, uploadFile) {
    console.log("选择文件触发===>>>");

}

// 删除轮播图
function handleRemoveSlideshow(uploadFile) {
    const index = goodsForm.slideshows.findIndex(item => item.image_url === uploadFile.url);
    if (index !== -1) {
        goodsForm.slideshows.splice(index, 1);
    }
}

// 详情图上传成功
function handleDetailImgSuccess(response, uploadFile) {
    goodsForm.detailImgs.push({
        goods_id: goodsForm.goods_id,
        image_url: response.url
    });
}

// 删除详情图
function handleRemoveDetailImg(uploadFile) {
    const index = goodsForm.detailImgs.findIndex(item => item.image_url === uploadFile.url);
    if (index !== -1) {
        goodsForm.detailImgs.splice(index, 1);
    }
}

// 添加标签
function addLabel() {
    goodsForm.labels.push({
        goods_id: goodsForm.goods_id,
        label: ''
    });
}

// 删除标签
function removeLabel(index) {
    goodsForm.labels.splice(index, 1);
}

// 添加规格类型
function addSpecification() {
    goodsForm.specificationsWithValues.push({
        goods_id: goodsForm.goods_id,
        speci_name: '',
        specis: []
    });
}

// 删除规格类型
function removeSpecification(index) {
    goodsForm.specificationsWithValues.splice(index, 1);
}

// 添加规格值
function addSpecValue(specIndex) {
    goodsForm.specificationsWithValues[specIndex].specis.push({
        specification_id: 0, // 后端生成
        specis_value: '',
        price: goodsForm.price
    });
}

// 删除规格值
function removeSpecValue(specIndex, valueIndex) {
    goodsForm.specificationsWithValues[specIndex].specis.splice(valueIndex, 1);
}

// 提交表单
function submitForm() {
    formRef.value.validate(async (valid) => {
        if (valid) {
            try {
                // 设置关联ID
                goodsForm.labels.forEach(label => {
                    label.goods_id = goodsForm.goods_id;
                });

                goodsForm.specificationsWithValues.forEach(spec => {
                    spec.goods_id = goodsForm.goods_id;
                });

                // 保存逻辑，调用API
                executeAddGoods();

                // 模拟API调用
                console.log('保存商品数据===>>', goodsForm);

                // 刷新列表
                // emit('refresh');
            } catch (error) {
                console.error('保存失败', error);
                ElMessage.error('保存失败: ' + error.message);
            }
        } else {
            ElMessage.warning('请填写完整表单内容');
            return false;
        }
    });
}

// 执行新增
async function executeAddGoods() {
    const res = await axios.post("/goodsManage/addGoods", goodsForm);

    console.log("执行新增结果--->", res);

    if (res.data.code == 1) {
        ElMessage.success('添加商品成功');
        dialogVisible.value = false;

        // 更新商品列表
        fetchGoods();
        return 1;
    }

    ElMessage.error('添加商品失败');

}

// 搜索商品
const searchGoods = () => {
    // 将页面重置到第一页
    currentPage.value = 1;
    fetchGoods();
};

// 分页处理
const handleSizeChange = (size) => {
    pageSize.value = size;
    fetchGoods();
};

const handleCurrentChange = (page) => {
    currentPage.value = page;
    fetchGoods();
};

// 显示轮播图预览
const showSlideshowDialog = (row) => {
    currentImages.value = row.slideshows;
    slideshowDialogVisible.value = true;
};

// 显示详情图预览
const showDetailImgDialog = (row) => {
    currentImages.value = row.detailImgs;
    detailImgDialogVisible.value = true;
};

// 推荐状态切换
const toggleRecommend = async (row) => {
    // 这里可以添加更新推荐状态的请求
    ElMessage.success(`商品 ${row.goods_name} 的推荐状态已更改为 ${row.recommend ? '推荐' : '不推荐'}`);
};

// 删除商品
const handleDelete = (row) => {
    ElMessageBox.confirm(
        `确定要删除商品"${row.goods_name}"吗？`,
        '删除确认',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }
    ).then(async () => {
        // 这里可以添加删除商品的请求
        executeDelete(row.goods_id);
    }).catch(() => {
        // 取消删除
    });
};

// 执行删除
async function executeDelete(goodsId) {
    console.log("删除商品ID--->", goodsId);


    const res = await axios.post(`/goodsManage/deleteGoods`, { goodsId: goodsId });

    console.log("删除商品结果--->", res);


    if (res.data.code == 1) {
        ElMessage.success('删除商品成功');
        fetchGoods();
        return 1;
    }

    ElMessage.error('删除商品失败');
}

// 编辑商品
function handleEditeGOodsInfo(goodsData) {
    // console.log("需要编辑的商品数据--->>>", goodsData);
    currentGoods.value = { ...goodsData } // 复制一份数据，避免直接修改原数据
    editDialogVisible.value = true
}

</script>

<style scoped>
#goods_container {
    box-sizing: border-box;
    padding: 20px;
}

.header-section {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
}

.search-bar {
    display: flex;
    gap: 10px;
}

.pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
}

.tag-item {
    margin-right: 5px;
    margin-bottom: 5px;
}

.image-preview-container {
    display: flex;
    flex-wrap: wrap;
    gap: 15px;
}

.image-preview-item {
    width: 200px;
    position: relative;
}

.image-preview-item .el-image {
    width: 100%;
    height: 150px;
    border-radius: 4px;
    overflow: hidden;
}

.image-actions {
    position: absolute;
    top: 5px;
    right: 5px;
    background-color: rgba(255, 255, 255, 0.7);
    border-radius: 4px;
    padding: 2px;
}

.image-upload-box {
    width: 200px;
    height: 150px;
    border: 1px dashed #ccc;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
}

.spec-container {
    margin-bottom: 20px;
}

.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
    border-radius: 10px;
}

.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
    line-height: 178px;
    border: solid 1px #918f8f;
    border-radius: 10px;
}
</style>